var express = require("express");
var router = express.Router();
const getTime = require("../../utils/getTime");
const getOrderNumber = require("../../utils/getOrderNumber");
const userModel = require("../../models/userModel");
const shopCartModel = require("../../models/shopCartModel");
const orderModel = require("../../models/orderModel");
const productModel = require("../../models/productModel");
const charProductModel = require("../../models/characteristicProductModel");

// 获取订单
router.get("/:userName", (req, res) => {
  const { userName } = req.params;
  orderModel
    .find({ userName })
    .select({ __v: 0 })
    .populate("items.productId")
    .populate("items.charProductId")
    .then((data) => {
      if (data.length === 0) {
        return res.json({
          code: 200,
          data: null,
          msg: "订单数据为空",
        });
      }
      return res.json({
        code: 200,
        data,
        msg: "获取订单信息成功",
      });
    })
    .catch((err) => {
      res.status(500).json({ message: err.message });
    });
});

// 点击购物车结算
router.post("/trade", async (req, res) => {
  const { userId, productIds, charProductIds } = req.body;
  try {
    let cart = await shopCartModel
      .findOne({ userId })
      .populate("items.productId")
      .populate("items.charProductId");
    let orderInfo = cart.items.filter((p) => {
      if (!p.charProductId) {
        return productIds.includes(p.productId._id.toString());
      }else {
        return charProductIds.includes(p.charProductId._id.toString())
      }
    });
    let total = 0;
    let count = 0
    orderInfo.forEach((p) => {
      total += p.price
      count += p.quantity
    });
    return res.json({
      code: 200,
      data: orderInfo,
      total: total.toFixed(2),
      count
    });
  } catch (err) {
    console.log(err);
    res.status(500).json({ message: err.message });
  }
});

// 点击立即购买
router.post('/confirm',async ( req,res) => {
  let {quantity,productId,charProductId} = req.body
  try {
    if(productId){
      let p =await productModel.findOne({_id:productId})
      if(quantity>p.quantity){
        return res.json({
          code:-1,
          msg:"库存不足"
        })
      }
      let total = (p.price * quantity).toFixed(2)
      let data = {productId:p,price:total,quantity}
      return res.json({
        code:200,
        data:[data],
        count:quantity,
        total,
        msg:"成功"
      })
    }else{
      let c =await charProductModel.findOne({_id:charProductId})
      if(quantity>c.quantity){
        return res.json({
          code:-1,
          msg:"库存不足"
        })
      }
      let total = (c.price * quantity).toFixed(2)
      let data = {charProductId:c,price:total,quantity}
      return res.json({
        code:200,
        data:[data],
        count:quantity,
        total,
        msg:"成功"
      })
    }
  } catch (err) {
    return res.status(500).json({ message: err.message })
  }
})

// 提交订单
router.post("/submit", async (req, res) => {
  const { userName, items, totalPrice,userAddr } = req.body;
  let orderNumber = getOrderNumber();
  let createdAt = getTime(new Date());
  try {
    let order = new orderModel({
      userName,
      orderNumber,
      items,
      totalPrice,
      createdAt,
      userAddr
    });
    let updatedOrder = await order.save();
    setTimeout(async () => {
      if (order.status === "待支付") {
        order.status = "已取消";
        await order.save();
        console.log(`Order ${order.orderNumber} has been cancelled.`);
      }
    }, 30 * 60 * 1000);
    return res.json({
      code: 200,
      data: updatedOrder,
      msg: "订单提交成功",
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// 订单支付
router.post("/pay", async (req, res) => {
  let { userId, orderNumber } = req.body;
  let userInfo = await userModel.findById(userId);
  let order = await orderModel.findOne({ orderNumber });
  let money = userInfo.money - order.totalPrice;
  try {
    if (money < 0) {
      return res.json({
        code: 200,
        data: null,
        msg: "用户余额不足，无法支付订单",
      });
    } else {
      userInfo.money -= order.totalPrice;
      order.status = "待发货";
      order.items.forEach(async (p) => {
        if(p.productId){
          let product = await productModel.findOne({_id:p.productId})
          product.quantity -= p.quantity
          await product.save()
        }else{
          let charProduct = await charProductModel.findOne({_id:p.charProductId})
          charProduct.quantity -= p.quantity
          await charProduct.save()
        }
      })
      await userInfo.save();
      await order.save();
      return res.json({
        code: 200,
        data: null,
        msg: "支付成功~",
      });
    }
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// 确认收货
router.put("/", (req, res) => {
  let { orderNumber } = req.body;
  let status = "已完成";
  orderModel
    .updateOne({ orderNumber }, { status })
    .then((data) => {
      if (!data.acknowledged) {
        return res.json({
          code: -1,
          msg: "确认收货失败",
          data: null,
        });
      }
      return res.json({
        code: 200,
        msg: "确认收货成功~",
        data: null,
      });
    })
    .catch((err) => {
      res.status(500).json({ message: err.message });
    });
});

// 删除订单
router.delete("/:orderNumber", (req, res) => {
  let { orderNumber } = req.params;
  orderModel
    .deleteOne({ orderNumber })
    .then((result) => {
      if (result.deletedCount !== 0) {
        return res.json({
          code: 200,
          msg: "删除成功",
          data: null,
        });
      }
      return res.json({
        code: -1,
        msg: "删除失败",
        data: null,
      });
    })
    .catch((err) => {
      res.status(500).json({ message: err.message });
    });
});

// 取消订单
router.post('/cancel', (req,res) => {
  let { orderNumber } = req.body;
  orderModel
    .updateOne({ orderNumber },{status:"已取消"})
    .then((result) => {
      if (result.deletedCount !== 0) {
        return res.json({
          code: 200,
          msg: "成功取消订单",
          data: null,
        });
      }
      return res.json({
        code: -1,
        msg: "取消订单失败",
        data: null,
      });
    })
    .catch((err) => {
      res.status(500).json({ message: err.message });
    });
})

module.exports = router;
